import socket
import threading
import requests
import json


# 智能问答机器人服务器
def to_user(data):
    result1 = requests.post("http://localhost:6032/api/check_qa",
                            data=json.dumps(data, ensure_ascii=False).encode('utf8').decode('latin-1')).json()
    result = json.dumps(result1, ensure_ascii=False, indent=2)
    result = json.loads(result)
    question = result['question_']
    questionOption = result['questionOption']
    questiontype = result['question_type']
    flag = result['flag']
    return question, questionOption, questiontype, flag, result1


def to_recommand(data):
    result = requests.post("http://localhost:6032/api/recommend",
                           data=json.dumps(data, ensure_ascii=False).encode('utf8').decode('latin-1')).json()

    return result


class RobotServer():
    def __init__(self, ip='127.0.0.1', port=8080, connectSize=100):
        '''
        port:服务器的端口号
        connectSize:默认的并发数量
        '''
        self.__ip = ip
        self.__port = port
        self.__connectSize = connectSize
        pass

    def startServer(self):
        # 服务器启动的主程序
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 套接字类型AF_INET, socket.SOCK_STREAM   tcp协议，基于流式的协议
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  # 对socket的配置重用ip和端口号
        server.bind((self.__ip, self.__port))  # 绑定端口号，写哪个ip就要运行在哪台机器上
        server.listen(self.__connectSize)  # 设置半连接池，最多可以连接多少个客户端
        while True:
            clientConn, clientAddr = server.accept()  # 在这个位置进行等待，监听端口号
            # 定义独立线程，处理每个请求
            wt = WorkThread(clientConn, clientAddr)
            wt.start()

            pass


class WorkThread(threading.Thread):
    def __init__(self, connection, addr, bufferSize=8096):
        threading.Thread.__init__(self)
        self.__connection = connection
        self.__addr = addr
        self.__bufferSize = bufferSize

    def run(self):
        receiveMsg = self.__connection.recv(self.__bufferSize)  # 接受套接字的大小，怎么发就怎么收
        receiveMsg = receiveMsg.decode('utf-8')
        type_dict = {"0": "填空", "1": "单项选择", "2": "多项选择"}
        global requests_data1
        if receiveMsg == '开始':
            data = {"question_num": "", "question_type": "", "question_anwser": [], "answer": {}, "question": "",
                    "code": 1}
            question, questionOption, questiontype, flag, requests_data1 = to_user(data)
            if isinstance(questionOption, list):
                questionOption = ','.join(questionOption)
            answer = "问题类型：" + type_dict[
                str(questiontype)] + "\n" + "问题：" + question + "\n" + "选项：" + questionOption + "\n"
            self.__connection.send(answer.encode("utf-8"))
        else:
            data = requests_data1
            data['question_anwser'] = []
            data['question_anwser'].append(receiveMsg)
            ans = data
            question, questionOption, questiontype, flag, requests_data1 = to_user(ans)
            if flag == 'continue':
                if isinstance(questionOption, list):
                    questionOption = ','.join(questionOption)
                answer = "问题类型：" + type_dict[
                    str(questiontype)] + "\n" + "问题：" + question + "\n" + "选项：" + questionOption + "\n"
                self.__connection.send(answer.encode("utf-8"))
            else:
                re_command = to_recommand(requests_data1['answer'])
                self.__connection.send(str(re_command).encode("utf-8"))

        self.__connection.close()  # 断开连接


if __name__ == "__main__":
    rs = RobotServer()
    rs.startServer()
